package com.xuan.shop.websocket;

import com.xuan.shop.dao.IUserDao;
import com.xuan.shop.entity.User;
import com.xuan.shop.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 实现和前端服务器连接，推送用户消息传入MQ以及数据传入数据库注册完成
 */

@Slf4j
@Component
@ServerEndpoint("/websocket/registerUser")
public class WebSocketSever {

    @Autowired
    private IUserService ius;
    //定义当前连接数量，设置成为线程安全
    private static final AtomicInteger nums=new AtomicInteger(0);
    private static final ConcurrentHashMap<Integer,Session> map=new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) throws IOException {
        int id=nums.incrementAndGet();
        log.info(id+"进行连接");
        map.put(id,session);
        session.getBasicRemote().sendText("后端连接成功");
    }

    @OnClose
    public void onClose(){
        map.remove(nums.decrementAndGet());
        log.info("断开websocket连接");
    }

    @RabbitListener(queues = {"queue_a","queue_b"})
    public void save(User user) throws IOException {
        ius.save(user);
        log.info("map"+map);
        if(!map.isEmpty()){
            Session session=map.get(nums.get());
            session.getBasicRemote().sendText("用户从mq消费成功");
        }
    }
}
